package com.hp.consumer.controller;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author dongxing
 **/
@RestController
@AllArgsConstructor(onConstructor_={@Autowired})
@RequestMapping("/user")
public class UserController {

    private final LoadBalancerClient loadBalancerClient;
    private final RestTemplate restTemplate;


    @GetMapping("/echo/{id}")
    public Object show(@PathVariable("id") String id) {
        //使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-producer");
//        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-producer");
        String url = String.format("http://%s:%s/mapper/config/user/%s",serviceInstance.getHost(),serviceInstance.getPort(),id);
        System.out.println("request url:"+url);
//        Map<String, Object> map = Maps.newHashMap();
//        map.put("pageNum",1);
//        map.put("pageSize",10);
//        String forObject = restTemplate.getForObject(url,String.class);
        Object forObject = restTemplate.getForObject(url, Object.class);
        return forObject;
    }

    @GetMapping("/echo1/{id}")
    public Object show1(@PathVariable("id") String id) {
        return restTemplate.getForObject("http://nacos-producer/mapper/config/user/"+id, Object.class);
    }

}
